Rendering Lists of Data in React🤖

September 11, 2021

Rendering Lists of Data 🤔

How to show a simple list item, a list of objects, Nesting Lists in React, and lastly, we will have a look at how to update the state of the React list. Lists can be idiomatic and non-idiomatic.

👉 Idiomatic means following the conventions of the language. You want to find the easiest and most common ways of accomplishing a task rather than porting your knowledge from a different language.

Idiomatic in the context of programming can usually be defined as "the most natural way to express something in a language"

Note that just because a piece of code is idiomatic, does not mean that it is clean or even concise. Many times you must make compromises.

So basically, idiomatic most commonly refers to the most common way to write something in a language, often times including "slang" (idioms). If a piece of code is not idiomatic, it may be perfectly readable, concise, clean, and correct, but it may feel/look awkward in the language used. It is a preference of taste as to whether rewriting such a piece of code idiomatically would actually be a good thing and must be judged on a case by case basis.

The non-idiomatic ways aren't wrong, but they usually take longer to type and they always take longer to read, for those who know the idioms.

The Non-React Way to Render a List

If you’re not accustomed to functional programming yet, your first inclination to render a list might be to create a new array, then iterate over the list and push JSX elements into it.

Example:

function NonIdiomaticList(props) {
  // Build an array of items
  let array = [];
  for(let i = 0; i < props.items.length; i++) {
    array.push(
      <Item key={i} item={props.items[i]} />
    );
  }

  // Render it
  return (
    <div>
      {array}
    </div>
  );
}

The React Way to Render a List

This component uses Array’s built-in map function to create a new array that has the same number of elements, and where each element is the result of calling the function you provide.

👉 To show the lists, we have to learn to use JavaScript’s Array.map() method. This method takes data transform to list view.

function ReactList(props) {
  return (
    <div>
      {props.items.map((item, index) => (
        <Item key={index} item={item} />
      ))}
    </div>
  );
}

The key prop

🛑 Remember!

React relies on the key to identify items in the list. Remember React uses a virtual DOM, and it only redraws the components that changed since the last render.

The best choice for a key is an item’s unique ID, if it has one.

The first time a component like IdiomaticReactList is rendered, React will see that you want to render a bunch of items, and it will create DOM nodes for them.

The next time that component renders, React will point out, “I have some list items on screen – are these ones different?” It will avoid recreating DOM nodes if it can tell that the items are the same.

But here’s the important trick: React can’t tell with a simple equality check, because every time a JSX element is created, that’s a brand new object, unequal to the old one.

So that’s where the key prop comes in. React can look at the key and know that even though this is not strictly === to the old , it actually is the same because the keys are the same.

This leads to a couple rules for keys. They must be:

👉 Unique – Every item in the list must have a unique key. So, person.firstName would not be a good choice, because it might not be unique).

👉 Permanent – An item’s key must not change between re-renders, unless that item is different. So, Math.random is a bad choice for a key because it will change every time and it might not be unique. Back to the problem at hand: why isn’t an item’s array index always a good choice for a key? Even it seems to be unique and permanent 🤔

If you know for sure that the list of items is static, then the array index is a good choice.

If on the other hand, the items could be reordered at some point, that will cause weird rendering bugs. If the list can be sorted, or you might replace items with new items (like fetching a new list from the server), things may not render as expected. Think about what happens in those situations: a new item replaces the one at index “0”, but to React, that item is unchanged because it’s still called “0”, so it doesn’t re-render.

if the list items have a unique id property of some sort, use that as a key.

Another example

We have a array of Vagies, and we want to display the Fruits list in React app, so here is the code that we will use to render the list items using .map() method.

import React from 'react';

function App() {
  const Vegies = [
    { name: 'Potato' },
    { name: 'Onion' },
    { name: 'Pepper' },
    { name: 'Aubergine' },
    { name: 'Pumpkin' },
    { name: 'Asparagus' },
    { name: 'Broccoli' },
    { name: 'Cabbage' }
  ];

  return (
    <div>
      {Vegies.map(data => (
        <p>{data.name}</p>
      ))}
    </div>
  );
}

export default App;

Render a List in React with Key

In the following React List example, we render a list of items that contain movie names and their respective id. We are using the .map() method to fetch the items from the Movies array, and every item has a unique key property.

🛑 Keys are used in React to figure out how to update a list, be it adding, updating, or deleting an item in a list.

Since React uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we provided a unique id to every list item.

If we don’t define key prop to display a list in JSX, we might get error.

Remember:

⚠️ Each child in a list should have a unique “key” prop.

import React from 'react';

function App() {
  const Movies = [
    { id: 1, name: 'Meet Joe Black' },
    { id: 2, name: 'Eternals' },
    { id: 3, name: 'Troy' },
    { id: 4, name: 'Original sin' },
    { id: 5, name: 'The Holiday' },
    { id: 6, name: 'Salt' },
    { id: 7, name: 'Seven Years in Tibet' },
    { id: 8, name: 'The Tourist' }
  ];

  return (
    <ul>
      {Movies.map(data => (
        <li key={data.id}> {data.name}</li>
      ))}
    </ul>
  );
}

export default App;

Display Object List in React

Displaying items from a list of objects in React is very simple. We can iterate over a list of objects using the .map() method in React JSX. Here is the example in which we mapped a list of objects and displayed them in the React app.

import React from 'react';

function App() {
  const Users = [
    {
      id: '01',
      name: 'Jude Law',
      email: 'jlaw@gmail.com',
      phone: '222-235-0123'
    },
    {
      id: '02',
      name: 'Angelina Jolie',
      email: 'fightclud@gmail.com',
      phone: '101-535-0122'
    },
  ];

  return (
    <ul>
      {Users.map((data) => (
        <li key={data.id}> 
          <p>{data.name}</p>
          <p>{data.email}</p>
          <p>{data.phone}</p>
        </li>
      ))}
    </ul>
  );
}

export default App;

React Nested Lists Example

A combination of two arrays and point out the nested view using the list data in React.

import React from 'react';

function App() {
  const users = [
    {
      id: '01',
      name: 'Jude Law',
      email: 'jlaw@gmail.com',
      phone: '222-235-0123'
    },
    {
      id: '02',
      name: 'Angelina Jolie',
      email: 'fightclud@gmail.com',
      phone: '101-535-0122'
    },
  ];

  const joinList = [users, users];

  return (
    <div>
        <ul>
            {joinList.map((nestedItem, i) => (
              <ul key={i}>
                <h3> List {i} </h3>
                {nestedItem.map(data => (
                  <li key={data.id}>
                    <div>{data.id}</div>
                    <div>{data.name}</div>
                    <div>{data.email}</div>
                    <div>{data.phone}</div>
                  </li>
                ))}
              </ul>
            ))}
          </ul>       
    </div>
  );
}

export default App;

Recap

to render a list in React follow the simple general rules:

👉 use Array.map()

👉 Do not use a for loop

👉 Avoid using array index as key

👉 Give each item a unique key

Happy Coding! 🌴 💻

Up next